package com.ysalliance.getFan.organization.ui.login;

import android.content.Intent;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.hbb20.CountryCodePicker;
import com.ysalliance.getFan.organization.LucasUtil;
import com.ysalliance.getFan.organization.R;
import com.ysalliance.getFan.organization.network.Network;
import com.ysalliance.getFan.organization.ui.OrganizationActivity;
import com.ysalliance.getFan.organization.ui.base.LucasBaseActivity;
import com.ysalliance.getFan.organization.ui.h5.CommonH5Activity;

import org.json.JSONObject;

import androidx.annotation.NonNull;
import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static com.ysalliance.getFan.organization.FanerConstant.AGREEMENT;
import static com.ysalliance.getFan.organization.FanerConstant.PROTOCOL;


/**
 * 登陆
 *
 * @author lucas
 * created at 2020-02-24 10:46
 */

public class LoginActivity extends LucasBaseActivity {

    //用户协议
    @BindView(R.id.tv_agreement)
    TextView tv_agreement;
    @BindView(R.id.tv_tiaokuan)
    TextView tv_tioakuan;
    @BindView(R.id.img_allow)
    ImageView img_allow;
    @BindView(R.id.ccp)
    CountryCodePicker ccp; //国家代码选择器

    private String country_code = "86";

    EditText etPhone;
    EditText etCode;
    TextView tvGetCode;
    TextView tvLogin;


    private TimeCount time;//倒计时
    private int durationTime = 60 * 1000;


    private Boolean is_allow_protocal = true;


    @Override
    public int bindContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void afterView() {
        super.afterView();


        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);
        tvGetCode = findViewById(R.id.tv_get_code);
        tvLogin = findViewById(R.id.tv_login);


        initClick();

    }


    public void initClick() {

        //用户协议的点击
        tv_agreement.setOnClickListener(v -> {
            Intent intent = new Intent(Utils.getApp(), CommonH5Activity.class);
            intent.putExtra("url", PROTOCOL);
            ActivityUtils.startActivity(intent);
        });

        //条款
        tv_tioakuan.setOnClickListener(v -> {
            Intent intent = new Intent(Utils.getApp(), CommonH5Activity.class);
            intent.putExtra("url", AGREEMENT);
            ActivityUtils.startActivity(intent);

        });

        //同意隐私条款
        img_allow.setOnClickListener(v -> {
            if (is_allow_protocal) {
                img_allow.setImageResource(R.mipmap.faner_protocal_disallow);
            } else {
                img_allow.setImageResource(R.mipmap.faner_protocal_allow);
            }
            is_allow_protocal = !is_allow_protocal;
        });

        //国家代码
        ccp.changeDefaultLanguage(CountryCodePicker.Language.CHINESE_SIMPLIFIED);
        ccp.setCountryPreference("CN,hk,mo,tw");
        ccp.showFlag(false);
        ccp.showNameCode(false);
        ccp.setOnCountryChangeListener(new CountryCodePicker.OnCountryChangeListener() {
            @Override
            public void onCountrySelected() {
                country_code = ccp.getSelectedCountryCode();
            }
        });

        time = new TimeCount(durationTime, 1000);

        //发送验证码
        tvGetCode.setOnClickListener(v->{
            if (etPhone.getText().toString().trim().equals("")) {
                ToastUtils.showShort("请输入手机号");
            } else if (etPhone.getText().toString().trim().length() < 5 || etPhone.getText().toString().trim().length() > 12) {
                //允许输入5-12位数字
                ToastUtils.showShort("请输入正确的手机号");
            } else {
                    getCode(country_code,etPhone.getText().toString().trim(),"1");
            }
        });

        //点击登录
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (etPhone.getText().toString().trim().equals("")) {
                    ToastUtils.showShort("请输入手机号");
                } else if (etCode.getText().toString().trim().equals("")) {
                    ToastUtils.showShort("请输入验证码");
                } else {
                    login("1", etPhone.getText().toString().trim(),etCode.getText().toString().trim(),"","","","");
                }
            }
        });


    }


    /**   获得验证码  */
    public void getCode(String country_code, String phone,String type){
        disposable = Network.getUtilApi()
                .getLoginCode(phone,type, country_code)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("验证码的返回", res);

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){
                            time.start();
                        }else {
                            String mymsg =  jsonObject.optString("message");
                            ToastUtils.showShort(mymsg);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });

    }

    /**  登陆  */
    public void login(String login_type, String mobile,String sms_code,String wei_id, String qq_id, String username, String user_pic){
        if(!is_allow_protocal){
            ToastUtils.showLong("请阅读用户协议和隐私条款~");
            return;
        }
        disposable = Network.getUtilApi()
                .login(login_type, mobile,sms_code ,wei_id,qq_id,username,user_pic, DeviceUtils.getUniqueDeviceId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(@NonNull ResponseBody responseBody) throws Exception {
                        String res = responseBody.string();
                        LogUtils.json("登陆接口返回", res);

                        JSONObject jsonObject = new JSONObject(  res  );
                        if(LucasUtil.isok(jsonObject.optString("status"))){
                            JSONObject jsonobject_str_data = new JSONObject(   jsonObject.optString("data")  );
                            //保存用户对象
                            LucasUtil.login_related(mContext, jsonobject_str_data.optString("user"));
                            ActivityUtils.startActivity(OrganizationActivity.class);
                            finish();
                        }else {
                            ToastUtils.showShort(jsonObject.optString("message"));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        Toast.makeText(mContext,"网络请求失败！", Toast.LENGTH_SHORT).show();
                    }
                });
    }


    //验证码计时器
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            if (tvGetCode != null) {
                tvGetCode.setText("重新发送");
                tvGetCode.setClickable(true);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            if (tvGetCode != null) {
                tvGetCode.setClickable(false);//防止重复点击
                tvGetCode.setText(millisUntilFinished / 1000 + "s");
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //防止time的内存泄露
        if (time != null) {
            time.cancel();
        }
    }
}
